package com.coocaa.app.lib.cleaner.utils;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import org.apache.http4.HttpResponse;
import org.apache.http4.HttpStatus;
import org.apache.http4.client.HttpClient;
import org.apache.http4.client.methods.HttpGet;
import org.apache.http4.impl.client.DefaultHttpClient;
import org.apache.http4.util.EntityUtils;

import java.io.Serializable;

/**
 * Created by Eric on 2017/7/18.
 */

public class HttpUtils {

    static class Beans{
        public static class ServerData implements Serializable{
            public int ret;
            public String msg;
            public String data;
        }
    }


    public static int getServerXDay() {
//        String url = "http://172.20.132.181:8081/appstorev3/getRemoteCommand.html?type=4";   //测试服务器
        String url = "http://tc.skysrt.com/appstore/appstorev3/getRemoteCommand.html?type=4";   //正式服务器
        String res = getWebDataByUrl(url);
        Beans.ServerData data = JSONObject.parseObject(res, Beans.ServerData.class);
        Log.d("server", "getServerXDay  data.data:" + data.data);
        int time = -1;
        if (data != null && data.data != null) {
            try {
                String server_time = data.data.substring(0, data.data.indexOf(","));
                time = Integer.valueOf(server_time);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.d("server", "getServerXDay  time:" + time);
        return time;
    }

    private static String getWebDataByUrl(String url) {
//        String httpUrl = "http://tc.skysrt.com/appstore/appstorev3/getYyqSwitch.html";
        Log.d("server", "getJsonFromWeb  url:" + url);
        String strResult = "";
        // HttpGet连接对象
        HttpGet httpRequest = new HttpGet(url);
        try {
            // 取得HttpClient对象
            HttpClient httpclient = new DefaultHttpClient();
            // 请求HttpClient，取得HttpResponse
            HttpResponse httpResponse = httpclient.execute(httpRequest);

            int statCode = httpResponse.getStatusLine().getStatusCode();
            // 请求成功
            if (statCode == HttpStatus.SC_OK) {
                // 取得返回的字符串
                strResult = EntityUtils.toString(httpResponse.getEntity());
            } else {
                Log.d("server", "HttpClient请求" + url + "出错，错误代码:" + statCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放http连接
            httpRequest.releaseConnection();
        }
        Log.d("server", "getJsonFromWeb  strResult:" + strResult);
        return strResult;
    }

}
